import instance from "./axios"
// 获取分类电影数据:
export function getCategoryMovie(current, state, isMorePage){
    let url = "/movie"
    if (current !== "全部") {
        url += `/${current}`
    }
    if(isMorePage){
        url += `?offset=${10 * state.currentPage}`
    }
    instance.get(url).then(res => {
        if(res.data.status === 200){
            if(isMorePage){
                state.currentPage += 1;
                res.data.data.movies.forEach(item => {
                    if(!state.movieId.has(item.id)){
                        state.movieId.add(item.id)
                        state.movieList.push(item);
                    }
                })
            }else{
                // 初次加载的数据不会出现重复
                state.movieList = res.data.data.movies;
                state.count = res.data.data.count;
                //切换时先清空set:
                state.movieId.clear();
                res.data.data.movies.forEach(item => {
                    state.movieId.add(item.id)
                })
            }
        }
    })
}

// 获取搜索电影数据
export function getSearchMovie(key, state, isMorePage){
    if (key != "") {
        let url = `/movie/search?q=${key}`
        if(isMorePage) {
            url += `&offset=${10 * state.currentPage}`;
            state.currentPage += 1;
        }
        instance.get(url).then(res => {
            if (res.data.status == 200) {
                if(isMorePage){
                    // 使用set id进行电影数据去重
                    res.data.data.movies.forEach(item => {
                        if(!state.movieId.has(item.id)){
                            state.movieId.add(item.id)
                            state.movieList.push(item);
                        }
                    })
                }else{
                    state.result = res.data.data.movies;
                    state.count = res.data.data.count;
                }
            }else{
                state.currentPage -= 1;
            }
        })
    } else {
        state.result = [];
        state.count = 0;
    }
}

// 获取电影详情数据:
export function getMovieInfo(id, state){
    instance.get(`/movie/info/${id}`).then(res => {
        if(res.data.status === 200){
            state.movie = res.data.data.movie
        }else{
            // 获取数据失败，强制返回首页:
            window.location.hash = "/"
        }
    })
}